package controller

import (
	"log"
	"net/http"
	"strconv"
	"strings"

	"gitee.com/chuanjinge/gopkgserv/api/response"
	"gitee.com/chuanjinge/gopkgserv/internal/dao"
	"gitee.com/chuanjinge/gopkgserv/internal/service/examsrv"
	"github.com/gin-gonic/gin"
)

// GetQuestionsRequest 请求参数
type GetQuestionsRequest struct {
	ExamID   int `form:"examId" json:"examId" binding:"required"`
	ViewOnly int `form:"viewOnly" json:"viewOnly"` // 是否只查看，true表示只查看
}

// GetQuestions 响应结构体
type QuestionOption struct {
	Id      int    `json:"id"`
	Label   string `json:"label"`
	Text    string `json:"text"`
	Checked int    `json:"checked,omitempty"`
}
type QuestionItem struct {
	ID         int              `json:"id"`
	Type       int              `json:"type"`
	TypeName   string           `json:"typeName"`
	Content    string           `json:"content"`
	Image      string           `json:"image"`
	Options    []QuestionOption `json:"options"`
	Answer     string           `json:"answer"`
	Analysis   string           `json:"analysis"`
	UserAnswer []string         `json:"userSelected"` // 用户答案，viewOnly=1 时返回
}
type GetQuestionsData struct {
	Metric struct {
		LeftTime int `json:"leftTime"`
	} `json:"metric"`
	Stat struct {
		Total    int `json:"total"`
		Unanswer int `json:"unanswer"`
		Corrent  int `json:"corrent"`
		Wrong    int `json:"wrong"`
	} `json:"stat"`
	List []QuestionItem `json:"list"`
}

// ExamController 控制器
type ExamController struct{}

// GetQuestions 获取考试试题
func (ec *ExamController) GetQuestions(c *gin.Context) {
	// 将此处从json改为query参数
	var req GetQuestionsRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		// 打印错误信息到日志中
		log.Printf("ShouldBindQuery error: %v", err)
		c.JSON(http.StatusBadRequest, response.BaseResponse{Code: 400, Msg: "参数错误"})
		return
	}
	log.Printf("GetQuestions request: %+v", req)
	// 查询 exam_exam_questions 表获取试题ID
	questionIDs, err := dao.GetQuestionIDsByExamID(req.ExamID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	// 查询试题内容
	questions, err := dao.GetQuestionsByIDs(questionIDs)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	// 查询选项
	var list []QuestionItem
	for _, q := range questions {
		options, _ := dao.GetOptionsByQuestionID(q.ID)
		var opts []QuestionOption
		for _, o := range options {
			opts = append(opts, QuestionOption{Id: o.ID, Label: o.OptionCode, Text: o.OptionContent})
		}

		item := QuestionItem{
			ID:       q.ID,
			Type:     q.Type,
			TypeName: dao.GetTypeName(q.Type),
			Content:  q.Content,
			Image:    "", // 可根据实际业务补充
			Options:  opts,
			Answer:   q.CorrectAnswer,
			Analysis: q.Explanation,
		}
		// viewOnly=1 时获取用户答案
		if req.ViewOnly == 1 {
			ansRecord, err := dao.GetUserAnswerByExamAndQuestion(req.ExamID, q.ID)
			if err == nil && ansRecord != nil {
				if ansRecord.UserAnswer != "" {
					item.UserAnswer = splitToArray(ansRecord.UserAnswer)

				} else {
					item.UserAnswer = []string{}
				}
			} else {
				item.UserAnswer = []string{}
			}
		}
		// 根据 UserAnswer 设置 Options 的 checked 属性
		if len(item.UserAnswer) > 0 {
			answerSet := make(map[string]struct{})
			for _, ans := range item.UserAnswer {
				answerSet[ans] = struct{}{}
			}
			for idx := range item.Options {
				if _, ok := answerSet[item.Options[idx].Label]; ok {
					item.Options[idx].Checked = 1
				} else {
					item.Options[idx].Checked = 0
				}
			}
		}
		list = append(list, item)
	}

	// 构造响应
	data := GetQuestionsData{}
	data.Metric.LeftTime = 3600 // 示例
	data.Stat.Total = len(list)
	data.Stat.Unanswer = 0 // 示例
	data.Stat.Corrent = 0  // 示例
	data.Stat.Wrong = 0    // 示例
	data.List = list
	c.JSON(http.StatusOK, response.Success(data))
}

// splitToArray 工具函数
// 可放到文件顶部
func splitToArray(s string) []string {
	var arr []string
	for _, v := range strings.Split(s, ",") {
		t := strings.TrimSpace(v)
		if t != "" {
			arr = append(arr, t)
		}
	}
	return arr
}

// Recent 查询用户最近一次考试结果
func (ec *ExamController) Recent(c *gin.Context) {
	userIdVal, exists := c.Get("userId")
	if !exists {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "未获取到用户信息"})
		return
	}
	userId, ok := userIdVal.(int64)
	if !ok {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "用户ID类型错误"})
		return
	}
	// 查询最近一次考试
	exam, err := examsrv.GetRecentExamByUserId(userId)
	if err != nil {
		c.JSON(http.StatusNotFound, response.BaseResponse{Code: 404, Msg: "未找到考试记录"})
		return
	}
	// 查询统计信息
	total, corrent, unanswered := examsrv.GetExamStat(exam.ExamID)
	resp := response.RecentExamResponse{
		ExamID:     exam.ExamID,
		Total:      total,
		Corrent:    corrent,
		Wrong:      total - corrent - unanswered,
		Unanswered: unanswered,
		ExamTime:   exam.ExamTime,
	}
	c.JSON(http.StatusOK, response.Success(resp))
}

// Record 查询考试记录
func (ec *ExamController) Record(c *gin.Context) {
	userIdVal, exists := c.Get("userId")
	if !exists {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "未获取到用户信息"})
		return
	}
	userId, ok := userIdVal.(int64)
	if !ok {
		c.JSON(http.StatusUnauthorized, response.BaseResponse{Code: 401, Msg: "用户ID类型错误"})
		return
	}
	page := c.DefaultQuery("page", "1")
	pageSize := c.DefaultQuery("pageSize", "20")
	// 查询考试记录及统计
	list, total, err := examsrv.GetExamRecords(userId, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, response.BaseResponse{Code: 500, Msg: err.Error()})
		return
	}
	totalPage := (total + atoi(pageSize) - 1) / atoi(pageSize)
	resp := response.ExamRecordResponse{
		List: list,
		Pagination: response.ExamRecordPagination{
			Page:      atoi(page),
			PageSize:  atoi(pageSize),
			Total:     total,
			TotalPage: totalPage,
		},
	}
	c.JSON(http.StatusOK, response.Success(resp))
}

// atoi 工具函数
func atoi(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
